﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace L4View.PresentationLayer
{
    public static class PagerExtension
    {
        public static ICollection<T> Page<T>(this ICollection<T> collection, int page, int pageSize)
        {
            return collection.Skip(page * pageSize).Take(pageSize).ToList();
        }

        public static int PageCount<T>(this ICollection<T> collection, int pageSize)
        {
            if (pageSize == 0)
                return 1;

            return (collection.Count + (pageSize - 1)) / pageSize;
        }
    }

    public class Pager<T>
    {
        private int _pageNumber;

        private int _pageSize;

        private ICollection<T> _collection;

        public Pager(ICollection<T> collection, int pageSize)
        {
            _pageNumber = 1;
            _pageSize = pageSize;
            _collection = collection;
        }

        public int PageNumber
        {
            get
            {
                return PageCount > 0 
                    ? _pageNumber 
                    : 0;
            }

            set
            {
                _pageNumber = value;

                if (_pageNumber < 1)
                    _pageNumber = 1;
                else if (_pageNumber > PageCount)
                    _pageNumber = PageCount;
            }
        }

        public int PageSize
        {
            get { return _pageSize; }
            set
            {
                int firstOnPageNumber = (_pageNumber - 1) * _pageSize;

                _pageSize = value;
                _pageNumber = ((firstOnPageNumber + (_pageSize - 1)) / _pageSize) + 1;
            }
        }

        public int PageCount
        {
            get { return _collection.PageCount(PageSize); }
        }

        public void First()
        {
            PageNumber = 1;
        }

        public void Last()
        {
            PageNumber = PageCount;
        }

        public void Prev()
        {
            _pageNumber -= _pageNumber == 1
                ? 0
                : 1;
        }

        public void Next()
        {
            _pageNumber += _pageNumber == PageCount
                ? 0
                : 1;
        }
    }
}